﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

using SSN.Utilities.Database;
using SSN.Utilities.Cache;
using SSN.Utilities.Security;
using SSN.Objects;
using SSN.BusinessFramework.News;

namespace SSN.WebFramework
{
    public class NewsManager
    {
        private SSNSecurityContext _ctx;
        private const int NEWS_ITEMS_DISPLAYED = 5;
        private static KeyValueCache<int, NewsItem> _newsCache = new KeyValueCache<int, NewsItem>(_initNewsCache, new TimeSpan(0, 5, 0));

        private static Dictionary<int, NewsItem> _initNewsCache()
        {
            SystemSecurityContext ctx = new SystemSecurityContext();
            List<NewsItem> list = DbManager.BossDb.CreateListFromQuery<NewsItem>(ctx, string.Format("SELECT * FROM {0} WHERE approved = 1 AND date_activate <= GetDATE() AND date_expire >= GETDATE()", NewsItem.TableName));
            Dictionary<int, NewsItem> table = new Dictionary<int, NewsItem>();
            foreach (NewsItem cc in list)
            {
                table[cc.ID] = cc;
            }

            return table;
        }

        private static NewsItem _getNewsItem(int id)
        {
            SystemSecurityContext sCtx = new SystemSecurityContext();
            NewsItem item = new NewsItem();
            if (item.Load(sCtx, id))
            {
                return item;
            }

            return null;
            
        }

        public NewsManager(SSNSecurityContext context)
        {
            _ctx = context;
        }

        /// <summary>
        /// Purges the news cache of news items.
        /// </summary>
        public void PurgeCache()
        {
            _newsCache.Purge(_ctx);
        }

        /// <summary>
        /// Returns the top news items.
        /// </summary>
        /// <param name="visiblity"></param>
        /// <returns></returns>
        public List<NewsItem> GetTopNewsItems(NewsVisibility visiblity)
        {
            return (from n in _newsCache.AllValues where n.Visibility.HasFlag(visiblity) orderby n.DateActivate descending, n.Priority descending select n).Take(NEWS_ITEMS_DISPLAYED).ToList();
        }

        public NewsItem GetNewsItem(int id)
        {
            return _newsCache[id];
        }
    }
}
